package com.spr.test.springboot.service;

import com.spr.test.springboot.controller.FileUploadController;
import com.spr.test.springboot.execption.MyExecption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class UploadFileService {
    @Value("${web.upload-path}")
    private String uploadPath;

    private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);

    public String uploadFile(MultipartFile file) throws MyExecption {
        if (file.isEmpty()) {
            return "文件为空";
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        String path = uploadPath;

        if (!file.getContentType().equals("image/png") && !file.getContentType().equals("image/jpeg")) {
            throw new MyExecption("文件类型错误,请上传图片类型");
        }

        // 获取文件名
        String fileName = UUID.randomUUID().toString().replace("-", "") + ".jpg";
        String abPath = File.separator + dateFormat.format(new Date()) + File.separator+fileName;
//        logger.info("上传的文件名为：" + fileName);
//        // 获取文件的后缀名
//        String suffixName = fileName.substring(fileName.lastIndexOf("."));
//        logger.info("上传的后缀名为：" + suffixName);
        // 文件上传后的路径
        // 解决中文问题，liunx下中文路径，图片显示问题
        // fileName = UUID.randomUUID() + suffixName;
        File dest = new File(path+abPath);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new MyExecption("失败：" + e.getMessage());
        }

        return abPath;
    }
}
